<?php

	require_once 'AppMessages.php';
	require_once 'ConnectDb.php';
	require_once 'BuildingService.php';
	require_once 'vo/BuildingVO.php';
	require_once 'ConnexionService.php';
	
	set_time_limit(0);

	class PlayerDatas {		
		
		public function getData($email, $password) {
			
			$data = null;
			
			if ( file_exists("users/".$email."_datas.txt") )
			{
				$data = unserialize(file_get_contents("users/".$email."_datas.txt"));
			}
			else
			{
				$data = array(
					"lastActiveTime" => time(),
					"gold" => 0,
					"gems" => 0,
					"mana" => 0,
					"level" => 0,
					"alliance" => "",
					"buildings"=>array()
				);
			}
			
			return $data;
		}
		
		public function setData( $email, $password, $data  ) {
		
			if ( $data == null )
			{
				$data = $this->getData($email,$password);
			}
			
			$data["lastActiveTime"] = time();
			file_put_contents("users/".$email."_datas.txt", serialize($data));
			
			$requete = 'UPDATE players SET lastActiveTime = :lastActiveTime WHERE email = :email AND password = :password';
			$connectDb = ConnectDb::getInstance()->getConnexion();
			$prep = $connectDb->prepare( $requete );
			$prep->bindValue(':email', $email, PDO::PARAM_STR);
			$prep->bindValue(':lastActiveTime', $data["lastActiveTime"], PDO::PARAM_INT);
			$prep->bindValue(':password', $password, PDO::PARAM_STR);
			$prep->execute();
			
			/*save*/
			return AppMessages::SUCCESS;
		}	
		
		public function addBuildingVOByName( $email, $password, $name, $uniqueName ) {
		
			$configVO = BuildingService::getInstance()->getBuildingConfigByName($name);
			$costGold = explode( ",", $configVO["costGold"] );
			$costMana = explode( ",", $configVO["costMana"] );
			$costGems = explode( ",", $configVO["costGems"] );
			
			$data = $this->getData($email, $password);
			
			// cout en ressources au level 1
			$priceGoldLevel1 = $costGold[0];
			$priceGemsLevel1 = $costGems[0];
			$priceManaLevel1 = $costMana[0];
			
			if ( $data["gold"] >= $priceGoldLevel1 && $data["gems"] >= $priceGemsLevel1 && $data["mana"] >= $priceManaLevel1 ) {
			
				$data["gold"] -= $priceGoldLevel1;
				$data["gems"] -= $priceGemsLevel1;
				$data["mana"] -= $priceManaLevel1;
				
				array_push( $data["buildings"], BuildingVO::buildFromConfig($configVO,$uniqueName) );
				
				$this->setData( $email, $password, $data );				
				
				return AppMessages::BUY_SUCCESS;
			}
			else {
				return AppMessages::CANNOT_BUY;
			}
		}
		
		public function getBuildingVOByUniqueName( $email, $password, $uniqueName ) {
		
			$data = $this->getData($email, $password);
			$buildings = $data["buildings"];
			$i = count($buildings);
			$buildingVO = null;
			
			while ( --$i > -1 )
			{
				$buildingVO = $buildings[$i];
				if ( $buildingVO->uniqueName == $uniqueName )
				{
					return $buildingVO;
				}
			}
			
			return null;
		}
		
		public function removeBuildingVOByUniqueName( $email, $password, $uniqueName ) {
		
			$data = $this->getData($email, $password);
			$buildings = $data["buildings"];
			$newTab = array();
			
			for ($i = 0; $i < count($buildings); $i++ ) {
				$buildingVO = $buildings[$i];
				if ( $buildingVO->uniqueName != $uniqueName ) {
					array_push($newTab, $buildingVO);
				}
			}
			
			$data["buildings"] = $newTab;
			
			$this->setData( 	$email, 
								$password, 
								$data
						);	
							
			return AppMessages::BUILDING_REMOVE_SUCCESS;
		}
		
		public function setGold($email,$password,$gold) {
			$data = $this->getData($email, $password);
			$data["gold"] = $gold;
			$this->setData($email, $password, $data); //$data est l'objet contenant toutes les ressources
			return $gold;
		}
		
		public function setMana($email,$password,$mana) {
			$data = $this->getData($email, $password);
			$data["mana"] = $mana;
			$this->setData($email, $password, $data); //$data est l'objet contenant toutes les ressources
			return $mana;
		}
		
		public function setGems($email,$password,$gems) {
			$data = $this->getData($email, $password);
			$data["gems"] = $gems;
			$this->setData($email, $password, $data); //$data est l'objet contenant toutes les ressources
			return $gems;
		}
		
		public function updateGameRessources($email, $password) {
		
			// unite d'actualisation des ressources = seconde;
			$data = $this->getData($email, $password);
			$elapsedTime = time() - (int)($data["lastActiveTime"]); // nombre de secondes écoulées depuis le dernier setData
			$buildings = $data["buildings"];
			$currentBuilding = null;
			$i = 0;
			$max = count($buildings);
			
			for ( $i = 0; $i < $max; $i++ )
			{
				$currentBuilding = $buildings[$i];
				
				// la production de gold et de mana étant calculée à la seconde
				// on multiplie cette production par le nombre de secondes écoulées depuis le dernier setData
				// pour obtenir le nombre de gold et de mana à ajouter
				
				$data["gold"] += $currentBuilding->prodGold * $elapsedTime;
				$data["mana"] += $currentBuilding->prodMana * $elapsedTime;
			}
			
			// on actualise les données
			$this->setData($email, $password, $data);
			return $data;
		}
		
		public function addFakeUsers()
		{
			
			$requete = 'TRUNCATE players';
			
			$connectDb = ConnectDb::getInstance()->getConnexion();
			$prep = $connectDb->prepare( $requete );
			$prep->execute();
		
			$i = 1000;
			$service = new ConnexionService();
			$data = null;
			$name = null;
			$password = "fakePassword";
			
			
			while ( --$i > -1 )
			{
				
				$name = "fake_".$i;
				$email = $name."@gmail.com";
				
				if ( file_exists("users/".$email."_datas.txt") )
				{
					unlink("users/".$email."_datas.txt");
				}
				
				$service->confirmInscription($name, $password, $email );
				$this->setGold($email, $password, 10000);
				$this->setMana($email, $password, 10000);
				$this->addBuildingVOByName($email, $password, "gold mine", "my_gold_mine_1");
			}
			
			return true;
		}
		
		
		public function writeBigFile()
		{
			$requete = 'SELECT email FROM players';
			
			$connectDb = ConnectDb::getInstance()->getConnexion();
			$prep = $connectDb->prepare( $requete );
			$prep->execute();
			$allDatas = $prep->fetchAll();
			$i = count($allDatas);
			$big = array();
			
			while( --$i > -1)
			{
				$email = $allDatas[$i]["email"];
				
				
				if ( !file_exists("users/".$email."_datas.txt") )
				{
					continue;
				}
				
				$big[$email] = unserialize(file_get_contents("users/".$email."_datas.txt"));
			}
			
			file_put_contents("users/all_users_datas.txt",serialize($big));
			
			return true;
		}		
		
		public function rwBig()
		{
			$big = unserialize(file_get_contents("users/all_users_datas.txt"));
			file_put_contents("users/all_users_datas.txt",serialize($big));
			
			return true;
		}
		
		public function massUpdateGameRessources(){
			
			$requete = 'SELECT email,lastActiveTime FROM players';
			
			$connectDb = ConnectDb::getInstance()->getConnexion();
			$prep = $connectDb->prepare( $requete );
			$prep->execute();
			$allDatas = $prep->fetchAll();
			$i = count($allDatas);
			$j = 0;
			$buildings = null;
			$playerData = null;
			$buildingVO = null;
			
			$currentTime = time();
			
			$configVO = BuildingService::getInstance()->getBuildingConfigByName("gold mine");
			$vo1 = BuildingVO::buildFromConfig($configVO, $uniqueName);
			
			$big = unserialize(file_get_contents("users/all_users_datas.txt"));
			
			
			
			while( --$i > -1)
			{
				$email = $allDatas[$i]["email"];
				
				/*
				if ( file_exists("users/".$email."_datas.txt") )
				{
					$playerData = unserialize(file_get_contents("users/".$email."_datas.txt"));
				}
				else
				{
				
					$playerData = array(
						"lastActiveTime" => $currentTime,
						"gold" => 0,
						"gems" => 0,
						"mana" => 0,
						"level" => 0,
						"alliance" => "",
						"buildings"=>array($vo1,$vo1,$vo1,$vo1,$vo1,$vo1,$vo1,$vo1,$vo1,$vo1)
					);
				}
				*/
				$playerData = $big[$email];
				
				
				$buildings = $playerData["buildings"];
				$j = count($buildings);
				$elapsedTime = $currentTime - (int)($allDatas[$i]["lastActiveTime"] );
				
				while ( --$j > -1 )
				{
					$buildingVO = $buildings[$j];
					$playerData["gold"] += $buildingVO->prodGold * $elapsedTime;
					$playerData["mana"] += $buildingVO->prodMana * $elapsedTime;
				}
				
				$playerData["lastActiveTime"] = $currentTime;
				$big[$email] = $playerData;
				//file_put_contents("users/".$email."_datas.txt", serialize($playerData));
			}
			
			file_put_contents("users/all_users_datas.txt",serialize($big));
			/*
			$requete = 'UPDATE players SET lastActiveTime = :lastActiveTime';
			$prep = $connectDb->prepare( $requete );
			$prep->bindValue(':lastActiveTime', $data["lastActiveTime"], PDO::PARAM_INT);
			$prep->execute();
			*/
			
			return true;
		}
	}
?>